//
//  HMCycleImageView.m
//  02-CycleImageView控件
//
//  Created by teacher on 2017/7/23.
//  Copyright © 2017年 teacher. All rights reserved.
//

#import "HMCycleImageView.h"
#import <Masonry/Masonry.h>
#import <SDWebImage/UIImageView+WebCache.h>

@interface HMCycleImageViewCell : UICollectionViewCell

@property (strong, nonatomic)   UIImageView     *imageView;

@end

@implementation HMCycleImageViewCell

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.imageView = [UIImageView new];
        self.imageView.contentMode = UIViewContentModeScaleAspectFill;
        self.imageView.clipsToBounds = YES;
        [self.contentView addSubview:self.imageView];
        [self.imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.contentView);
        }];
    }
    return self;
}


@end



@interface HMCycleImageView () <UICollectionViewDataSource,UICollectionViewDelegate,UIScrollViewDelegate>

@property (strong, nonatomic)   UICollectionView        *collectionView;

@property (strong, nonatomic)   UIPageControl           *pageControl;

@end

@implementation HMCycleImageView {
    NSInteger       _count;
    NSTimer         *_timer;
}


- (void)removeFromSuperview {
    [super removeFromSuperview];
    [self clearTimer];
}

#pragma mark - 属性重写 -
- (UICollectionView *)collectionView {
    if(_collectionView == nil) {
        UICollectionViewFlowLayout *layout = [UICollectionViewFlowLayout new];
        
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.pagingEnabled = YES;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        [_collectionView registerClass:[HMCycleImageViewCell class] forCellWithReuseIdentifier:@"CELL"];
        
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        [self addSubview:_collectionView];
        
        [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self);
        }];
    }
    
    return _collectionView;
}

- (UIPageControl *)pageControl {
    if(_pageControl == nil) {
        _pageControl = [UIPageControl new];
        [self addSubview:_pageControl];
        [_pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(self);
            make.height.mas_equalTo(40);
        }];
    }
    
    return _pageControl;
}

#pragma mark - 自动轮播器滚动 -
- (void)doTimer {
    [self.collectionView setContentOffset:CGPointMake(self.collectionView.contentOffset.x + self.collectionView.frame.size.width, self.collectionView.contentOffset.y) animated:YES];
    
    NSInteger idx = (self.collectionView.contentOffset.x + self.collectionView.frame.size.width) / self.collectionView.frame.size.width;
    
    self.pageControl.currentPage = idx % _count;
    
    
}
- (void)startTimer {
    [self clearTimer];
    _timer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(doTimer) userInfo:nil repeats:YES];
}

- (void)clearTimer {
    if(_timer != nil) {
        if([_timer isValid]) [_timer invalidate];
    }
    _timer = nil;
}



#pragma mark - 公共代码 -
- (void)reloadData {
    _count = 0;
    if(self.dataSource && [self.dataSource respondsToSelector:@selector(numberOfItemsInCycleImageView:)]) {
        _count = [self.dataSource numberOfItemsInCycleImageView:self];
    }
    
    [self.collectionView reloadData];
    
    self.pageControl.currentPageIndicatorTintColor = self.currentPageControlColor;
    self.pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
    self.pageControl.numberOfPages = [self.dataSource numberOfItemsInCycleImageView:self];
    self.pageControl.currentPage = 0;
    
    [self layoutIfNeeded];
    // 初始化collectionView 位置
    [self.collectionView setContentOffset:CGPointMake(self.collectionView.frame.size.width *  500 * _count, 0)];
    
    
    [self startTimer];
}

#pragma mark - UICollectionViewDataSource -
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _count * 1000;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    HMCycleImageViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CELL" forIndexPath:indexPath];
    
    NSURL *url = nil;
    
    NSInteger idx = indexPath.row % _count;
    if(self.dataSource && [self.dataSource respondsToSelector:@selector(cycleImageView:urlForImageViewAtIndex:)]) {
        url = [self.dataSource cycleImageView:self urlForImageViewAtIndex:idx];
    }
    
    if(url != nil) {
        if(self.placeholderImage == nil) {
            [cell.imageView sd_setImageWithURL:url];
        } else {
            [cell.imageView sd_setImageWithURL:url placeholderImage:self.placeholderImage];
        }
        
    }
    
    return cell;
}

#pragma mark - UICollectionViewDelegate -
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return self.bounds.size;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsZero;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}

#pragma mark - UIScrollViewDelegate -
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self clearTimer];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    NSInteger idx = scrollView.contentOffset.x / scrollView.frame.size.width;
    
    self.pageControl.currentPage = idx % _count;
    
    [self startTimer];
}
@end
